package com.panshi.realm;

import com.panshi.modules.service.SysUserService;
import com.panshi.vo.SysMenuVO;
import com.panshi.vo.SysRoleVO;
import com.panshi.vo.SysUserVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class CustomerRealm extends AuthorizingRealm {

    @Autowired
    private SysUserService sysUserApi;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String primaryPrincipal =(String) principals.getPrimaryPrincipal();
        SysUserVO byUsername =sysUserApi.getSysUserByUsername(primaryPrincipal);

        List<SysMenuVO> menuList = byUsername.getSysMenus();

        List<SysRoleVO> roleList = byUsername.getSysRoles();

        log.info("授权====================================================================>{}",byUsername);
        //授权角色信息
        if(! CollectionUtils.isEmpty(roleList)){

            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

            List<String> collect = roleList.stream().map(SysRoleVO::getRolename).collect(Collectors.toList());
            info.addRoles(collect);

            //授权权限信息
            if(! CollectionUtils.isEmpty(menuList)){
                for(SysMenuVO menu : menuList){
                    System.out.println(menu);
                    info.addStringPermission(menu.getPermission());
                }
            }
            return info;
        }

        return null;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        String principal = (String) token.getPrincipal();
        SysUserVO sysUserVO =sysUserApi.getSysUserByUsername(principal);

        log.info("认证==------------------------------------------------------------------------------>{}",sysUserVO);
        if(null != sysUserVO ){
            return new SimpleAuthenticationInfo(sysUserVO.getUsername(),sysUserVO.getPassword(),this.getName());
        }
        return null;
    }
}
